package com.framework.web.restful.util;

import com.framework.web.restful.doamin.MethodMappingBean;
import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;

public class RestfulMethodMappingReader {
	/** WEB端调用*/
	public static final int WEB_ALARM = 0;
	/** APP端*/
	public static final int APP_ALARM = 1;
	/** OUTSIDE端*/
	public static final int OUTSIDE = 2;
	/** 日志。 */
	private static final Logger logger = Logger.getLogger(RestfulMethodMappingReader.class);

	/** WEB配置文件classPath */
	private static final String WEB_PATH = "interface/web-api-method-mapping.xml";
	/** APP配置文件classPath */
	private static final String APP_PATH = "interface/app-api-method-mapping.xml";
	/** OUTSIDE配置文件classPath */
	private static final String OUTSIDE_PATH = "interface/outside-api-method-mapping.xml";
	/**
	 * 读取配置文件转化为MethodMappingBean对象。
	 * @param div 0 -> WEB, 1-> APP
	 * @return
	 */
	public MethodMappingBean read(int div) {
		MethodMappingBean ret = null;
		switch (div) {
		case WEB_ALARM:
			ret = read(WEB_PATH);
			break;
		case APP_ALARM:
			ret = read(APP_PATH);
			break;
		case OUTSIDE:
			ret = read(OUTSIDE_PATH);
			break;
		default:
			logger.info("请填写正确的区分：0 -> WEB, 1-> APP！2-> OUTSIDE");
			break;
		}
		return ret;
	}
	
	/**
	 * 读取配置文件转化为MethodMappingBean对象。
	 * @param xmlPath
	 * @return
	 */
	private MethodMappingBean read(String xmlPath) {
		MethodMappingBean ret = null;
    	ClassPathResource xml = new ClassPathResource(xmlPath);
        JAXBContext jc;
		try {
			jc = JAXBContext.newInstance(MethodMappingBean.class);
	        Unmarshaller unmar = jc.createUnmarshaller();
	        ret = (MethodMappingBean)unmar.unmarshal(xml.getInputStream());
		} catch (JAXBException e) {
			logger.info("从配置文件中读取数据失败！");
			e.printStackTrace();
		} catch (IOException e) {
			logger.info("从配置文件中读取数据失败！");
			e.printStackTrace();
		}
		return ret; 
	}
}
